package com.xzy.service.impl;

import com.xzy.custom.Page;
import com.xzy.entities.BookInformation;
import com.xzy.mapper.BookInformationMapper;
import com.xzy.mapper.BookRepertoryMapper;
import com.xzy.service.BookInformationService;
import com.xzy.web.form.BookInformationForm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * TODO70
 *
 * @author Administrator
 * ClassName: BookInfromationServiceImpl
 * date: 2021/12/3 14:51
 */
@Service
public class BookInformationServiceImpl implements BookInformationService {

    @Autowired
    private BookInformationMapper bookInformationMapper;
    @Autowired
    private BookRepertoryMapper bookRepertoryMapper;

    /** 图片存放位置 **/
    private final static String IMAGEPATH="F:\\IdeaProject\\xzy_graduate\\borrow_books\\src\\main\\resources\\image";

    @Override
    public List<BookInformation> findAllBookInformation(Page page,String name) {
        return bookInformationMapper.findAllBookInformation(page,name);
    }

    @Override
    public Integer findBookInformationCount(Page page,String name) {
        return bookInformationMapper.findBookInformationCount(page,name);
    }

    @Override
    public void deleteById(int parseInt) {
        bookRepertoryMapper.deleteByBookId(parseInt);
        bookInformationMapper.deleteById(parseInt);
    }

    @Override
    public BookInformation findById(Integer id) {
        return bookInformationMapper.findById(id);
    }

    @Override
    public Boolean saveFile(MultipartFile file, String uuid, Integer id) {
        File path = path(file.getContentType());
        String filename = file.getOriginalFilename();
        BookInformation picture = new BookInformation();
        picture.setUuid(uuid);
        picture.setFilename(filename);
        String imagesUrl = path.getAbsolutePath();
        picture.setImagesUrl(imagesUrl);
        File saveFile = new File(path,uuid);
        try {
            if (id != null){
                bookInformationMapper.updateFileById(picture,id);
            }else if (id == null){
                bookInformationMapper.saveFile(picture);
            }
            file.transferTo(saveFile);
            return true;
        }catch (IllegalStateException | IOException e){
            e.printStackTrace();
            return false;
        }
    }

    private File path(String content){
        File pat = new File("d:\\jeecgs");
        File path = new File(BookInformationServiceImpl.IMAGEPATH);
        if(!pat.isDirectory()){
            pat.mkdir();
        }
        if (!path.isDirectory()){
            path.mkdir();
        }
        return path;
    }

    /**
     * 下载
     * @param request
     * @param uuid
     * @return
     */
    @Override
    public void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
        BookInformation fileEntity = bookInformationMapper.findByUuid(uuid);
        String filename = fileEntity.getFilename();
        filename = getStr(request, filename);
        File file = new File(fileEntity.getImagesUrl(), uuid);
        if(file.exists()) {
            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
                response.setContentType("application/x-msdownload");
                response.addHeader("Content-Disposition", "attachment; filename=" + filename );
                ServletOutputStream out = response.getOutputStream();
                byte[] buf=new byte[2048];
                int n=0;
                while((n=fis.read(buf))!=-1){
                    out.write(buf, 0, n);
                }
                fis.close();
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void updataById(BookInformationForm form) {
        bookInformationMapper.updataById(form);
    }

    @Override
    public void insertInformation(BookInformationForm form) {
        bookInformationMapper.insertInformation(form);
    }

    @Override
    public BookInformation findByUuid(String uuid) {
        return bookInformationMapper.findByUuid(uuid);
    }

    @Override
    public List<BookInformation> findAllBookInformation1() {
        return bookInformationMapper.findAllBookInformation1();
    }

    @Override
    public List<BookInformation> findByBookName(String bookName) {
        return bookInformationMapper.findByBookName(bookName);
    }

    @Override
    public List<BookInformation> findBookInformationList() {
        return bookInformationMapper.findBookInformationList();
    }

    @Override
    public BookInformation xwfindById(Integer id) {
        return bookInformationMapper.xwfindById(id);
    }

    @Override
    public List<BookInformation> findByBookId(List<Integer> bookId, Integer userId) {
        return bookInformationMapper.findByBookId(bookId,userId);
    }

    @Override
    public List<BookInformation> findByBookIdAndBookName(List<Integer> bookId, String bookName, Integer userId) {
        return bookInformationMapper.findByBookIdAndBookName(bookId,bookName,userId);
    }

    @Override
    public BookInformation xwfindBorrowById(Integer borrowId) {
        return bookInformationMapper.xwfindBorrowById(borrowId);
    }

    @Override
    public List<BookInformation> findAllBook() {
        return bookInformationMapper.findAllBook();
    }

    private String getStr(HttpServletRequest request, String filename) {
        String downloadFileName = null;
        //仅提供了部分代码，因为我们已经明确问题的所在，知道修改那一部分了，（代码中downloadFileName 即代表 *=utf-8'zh_cn'文件名.xx部分）
        String agent = request.getHeader("USER-AGENT");
        try {
            if(agent != null && agent.toLowerCase().indexOf("firefox") > 0){
                //downloadFileName = "=?UTF-8?B?" + (new String(Base64Utils.encode(fileName.getBytes("UTF-8")))) + "?=";
                //设置字符集
                downloadFileName = "=?UTF-8?B?" + Base64Utils.encodeToString(filename.getBytes("UTF-8")) + "?=";
            }else{
                downloadFileName =  java.net.URLEncoder.encode(filename, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return downloadFileName;
    }
}
